const config = require("../config.js")
const crypto = require("../utils/crypto/sha256")

module.exports = {
  chooseImageAndGetBase64Data() {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          const fs = wx.getFileSystemManager();
          fs.readFile({
            filePath: tempFilePaths[0],
            encoding: 'base64',
            success: (res) => {
              const base64Data = res.data
              return resolve('data:<MIME类型>;base64,' + base64Data)
            },
            fail: function (err) {
              return resolve(false)
              console.error('读取文件失败：', err);
            }
          });
        },
        fail: function (err) {
          return resolve(false)
          console.error('选择图片失败：', err);
        }
      })
    })
  },
  encodeString(string) {

    function isLetter(code) {
      if (code >= 65 && code <= 90) {
        return 1
      }
      if (code >= 97 && code <= 122) {
        return 1
      }
      if (code > 90 && code < 97) {
        return 2
      }
      if (code < 65) {
        return 0
      }
      return 2
    }

    function getNumberString(n, x) {
      n = JSON.stringify(n)
      for (let i = n.length; i < x; i++) {
        n = '0' + n
      }
      return n
    }

    string = string.split('')
    let string1 = ''
    for (let i = 0; i < string.length; i++) {
      string1 += JSON.stringify(JSON.stringify(string[i].charCodeAt(0)).length) + JSON.stringify(string[i].charCodeAt(0))
    }
    string1 = string1.split('')
    for (let i = 0; i < string1.length; i++) {
      if (string1[i] == '0') {
        continue
      }
      let c = i
      let ss = string1[c]
      while (true) {
        let cd = isLetter(parseInt(ss))
        if (cd == 2) {
          break
        }
        if (cd == 1) {
          string1[c] = String.fromCharCode(parseInt(ss))
          for (let i1 = i; i1 < c; i1++) {
            string1[i1] = '-'
          }
          i = c
          break
        }
        c++
        if (c == string1.length) {
          break
        }
        ss += string1[c]
      }
    }
    for (let i = 0; i < string1.length - 1; i++) {
      if (string1[i] == '2' && string1[i + 1] == '2') {
        string1[i] = '?'
        string1[i + 1] = '-'
      }
    }
    let string2 = []
    for (let i = 0; i < string1.length; i++) {
      if (string1[i] == '-') {
        continue
      }
      string2.push(JSON.stringify((string1[i].charCodeAt(0) - string1[i].charCodeAt(0) % 52) / 52) + getNumberString(string1[i].charCodeAt(0) % 52, 2))
    }
    let string3 = ''
    for (let i = string2.length - 1; i >= 0; i--) {
      string3 += string2[i]
    }
    string3 = string3.split('')
    let string4 = []
    for (let i = 0; i < string3.length; i += 2) {
      let ch = string3[i]
      if (i + 1 != string3.length) {
        ch += string3[i + 1]
      }
      if (parseInt(ch) < 52 && ch.length == 2) {
        if (parseInt(ch) < 26) {
          string4.push(String.fromCharCode(parseInt(ch) + 65))
        } else {
          string4.push(String.fromCharCode(parseInt(ch) + 97 - 26))
        }
      } else {
        string4.push(ch)
      }
    }
    let string5 = ''
    for (let i = 0; i < string4.length; i++) {
      string5 += string4[i]
    }
    return string5
  },
  decodeString(string) {
    function getNumberString(n, x) {
      n = JSON.stringify(n)
      for (let i = n.length; i < x; i++) {
        n = '0' + n
      }
      return n
    }

    string = string.split('')
    for (let i = 0; i < string.length; i++) {
      if (string[i].charCodeAt(0) >= 48 && string[i].charCodeAt(0) <= 56) {
        continue
      }
      if (string[i].charCodeAt(0) <= 90) {
        string[i] = getNumberString(string[i].charCodeAt(0) - 65, 2)
      } else {
        string[i] = getNumberString(string[i].charCodeAt(0) - 97 + 26, 2)
      }
    }
    let string2 = ''
    for (let i = 0; i < string.length; i++) {
      if (string[i] == '-8') {
        string2 += '9'
        continue
      }
      string2 += string[i]
    }
    string2 = string2.split('')
    let string3 = []
    for (let i = 0; i < string2.length; i += 3) {
      string3.push(getNumberString(parseInt(string2[i]) * 52 + parseInt(string2[i + 1] + string2[i + 2]), 3))
    }
    let string4 = []
    for (let i = string3.length - 1; i >= 0; i--) {
      string4.push(String.fromCharCode(parseInt(string3[i])))
    }
    let string5 = ''
    for (let i = 0; i < string4.length; i++) {
      if (string4[i] == '?') {
        string5 += '22'
        continue
      }
      if ((string4[i].charCodeAt(0) >= 48 && string4[i].charCodeAt(0) <= 57) == false) {
        string5 += JSON.stringify(string4[i].charCodeAt(0))
        continue
      }
      string5 += string4[i]
    }
    string5 = string5.split('')
    let string6 = ''
    for (let i = 0; i < string5.length; i++) {
      let n = parseInt(string5[i])
      let s = ''
      for (let i1 = 0; i1 < n; i1++) {
        s += string5[i + 1 + i1]
      }
      string6 += String.fromCharCode(parseInt(s))
      i += n
    }
    return string6
  },
  requestMethod(apiName, data = {}) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: config.serverURL + apiName,
        method: 'POST',
        data: {
          data: this.encodeString(JSON.stringify(data))
        },
        success: res => {
          if (res.data == '非法请求') {
            return resolve(this.requestMethod(apiName, data))
          }
          return resolve(res.data)
        }
      })
    })
  },
  sha256(string) {
    return wordsToHex(crypto(string).words)
  },
  getLoginCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          return resolve(res.code)
        },
        fail() {
          console.log('请登录微信开发者工具')
        }
      })
    })
  },
  uploadFile(filePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: config.serverURL + '/file/upload',
        filePath: filePath,
        name: 'file',
        header: {
          'content-type': 'multipart/form-data'
        },
        success: (uploadRes) => {
          this.requestMethod('/log', {
            content: JSON.stringify(uploadRes)
          })
          console.log(uploadRes)
          return resolve(JSON.parse(uploadRes.data).results)
        },
        fail: function (e) {
          this.requestMethod('/log', {
            content: JSON.stringify(e)
          })
          console.log(e)
          return resolve(false)
        }
      })
    })
  },
  waitSeconds(n) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        return resolve()
      }, n * 1000);
    })
  },
  formatTime(inputTime) {
    function getPeriod(hours) {
      if (hours >= 0 && hours < 6) {
        return '凌晨';
      } else if (hours >= 6 && hours < 11) {
        return '上午';
      } else if (hours >= 11 && hours < 14) {
        return '中午';
      } else if (hours >= 14 && hours < 18) {
        return '下午';
      } else {
        return '晚上';
      }
    }
    const date = new Date(inputTime);
    const now = new Date();
    const oneDay = 24 * 60 * 60 * 1000;
    const twoDays = 2 * oneDay;
    const diff = Math.abs(now - date);
    const currentYear = now.getFullYear();
    const currentMonth = String(now.getMonth() + 1).padStart(2, '0');
    const currentDay = String(now.getDate()).padStart(2, '0');
    const currentHours = String(now.getHours()).padStart(2, '0');
    const currentMinutes = String(now.getMinutes()).padStart(2, '0');
    const inputYear = date.getFullYear();
    const inputMonth = String(date.getMonth() + 1).padStart(2, '0');
    const inputDay = String(date.getDate()).padStart(2, '0');
    const inputHours = String(date.getHours()).padStart(2, '0');
    const inputMinutes = String(date.getMinutes()).padStart(2, '0');
    const inputDayOfWeek = date.toLocaleString('zh-CN', {
      weekday: 'long'
    });
    if (diff < oneDay) {
      const period = getPeriod(inputHours);
      return `${period} ${inputHours}:${inputMinutes}`;
    } else if (diff < twoDays) {
      const period = getPeriod(inputHours);
      return `昨天${period} ${inputHours}:${inputMinutes}`;
    } else {
      return `${inputYear}年${inputMonth}月${inputDay}日 ${inputHours}:${inputMinutes} ${inputDayOfWeek}`;
    }
  },
  checkUserPer(userData, item) {
    let per = {
      sh: userData.type == 'admin',
      cl: userData.type == 'admin',
      pj: userData.type == 'admin',
      ch: false,
      sc: userData.type == 'admin',
      bhData: undefined,
      process: [{
        type: 'add',
        item: item
      }]
    }
    if (item.account == userData.account) {
      per.pj = true
    }
    for (let i = 0; i < userData.per.rp.length; i++) {
      if (userData.per.rp[i].XQ == item.XQ && userData.per.rp[i].LX == item.LX) {
        per.cl = true
        break
      }
    }
    for (let i = 0; i < userData.per.rep.length; i++) {
      if (userData.per.rep[i].XQ == item.XQ && userData.per.rep[i].LX == item.LX) {
        per.sh = true
        break
      }
    }
    if (userData.per.sadmin || userData.per.admin) {
      per.sh = true
    }
    if (item.account == userData.account && item.content3.length == 0) {
      per.ch = true
    }
    if (item.content3.length != 0 && item.content3[item.content3.length - 1].type == 'reject' && item.content2 == '') {
      per.bhData = item.content3[item.content3.length - 1]
    }
    for (let i = 0; i < item.content3.length; i++) {
      per.process.push(item.content3[i])
    }
    if (item.sat != 6 && item.sat != 0) {
      per.process.push({
        type: 'comment',
        sat: item.sat,
        satTime: item.satTimeRead
      })
    }
    return per
  },
  formatTimeNew(inputTime = new Date()) {
    function getPeriod(hours) {
      if (hours >= 0 && hours < 6) {
        return '凌晨';
      } else if (hours >= 6 && hours < 11) {
        return '上午';
      } else if (hours >= 11 && hours < 14) {
        return '中午';
      } else if (hours >= 14 && hours < 18) {
        return '下午';
      } else {
        return '晚上';
      }
    }

    function getWeekName(n) {
      switch (n) {
        case 0:
          return '星期天'
        case 1:
          return '星期一'
        case 2:
          return '星期二'
        case 3:
          return '星期三'
        case 4:
          return '星期四'
        case 5:
          return '星期五'
        case 6:
          return '星期六'
      }
    }
    let currentTime = new Date()
    let oneDaySecond = 86400000
    let currentDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime.getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000)
    let lastDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime.getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 - oneDaySecond)
    let nextDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime.getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 + oneDaySecond)
    let nextDayEnd = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime.getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 + oneDaySecond * 2)
    let prefix = ''
    if (inputTime >= currentDayStart && inputTime < nextDayStart) {
      prefix = '今天'
    }
    if (inputTime >= lastDayStart && inputTime < currentDayStart) {
      prefix = '昨天'
    }
    if (inputTime >= nextDayStart && inputTime < nextDayEnd) {
      prefix = '明天'
    }
    if (prefix == '') {
      prefix = (inputTime.getFullYear() == currentTime.getFullYear() ? '' : inputTime.getFullYear().toString() + '年') + (inputTime.getMonth() + 1).toString() + '月' + inputTime.getDate() + '日 '
    }
    prefix += getPeriod(inputTime.getHours()) + ' '
    prefix += inputTime.getHours().toString() + ':'
    if (inputTime.getMinutes() < 10) {
      prefix += '0'
    }
    prefix += inputTime.getMinutes().toString() + ' '
    prefix += getWeekName(inputTime.getDay())
    return prefix
  },
  showComPhoneNumberList(statusBarHeight, contentHeight, loginedUserInfo, id) {
    wx.navigateTo({
      url: '/pages/comPhoneNumberList/comPhoneNumberList?data=' + JSON.stringify({
        statusBarHeight: statusBarHeight,
        contentHeight: contentHeight,
        id: id,
        loginedUserInfo: loginedUserInfo
      }),
    })
  },
  showToast(title) {
    wx.showToast({
      title: title,
      icon: 'none'
    })
  },
  getChartData(data, SF, XQ, LX, dx) {
    // console.log(data)
    return data
    // data = JSON.parse(JSON.stringify(data.dimension))
    // let titles = undefined
    // let rdata = {}
    // for(let i1=0;i1<Object.keys(data).length;i1++){
    //   let cSF = Object.keys(data)[i1]
    //   if(SF==cSF || SF=='全部'){
    //     for(let i2=0;i2<Object.keys(data[cSF]).length;i2++){
    //       let cXQ = Object.keys(data[cSF])[i2]
    //       if(XQ==cXQ || XQ=='全部'){
    //         for(let i3=0;i3<Object.keys( data[cSF][cXQ] ).length;i3++){
    //           let cLX = Object.keys( data[cSF][cXQ] )[i3]
    //           if(LX==cLX || LX=='全部'){
    //             let cTimeLine = data[cSF][cXQ][cLX].timeLine[dx]
    //             let cTimeLineTitles = data[cSF][cXQ][cLX].timeLine[dx + 'Titles']
    //             if(titles==undefined){
    //               titles = cTimeLineTitles
    //               rdata = cTimeLine
    //             }else{
    //               for(let i=0;i<rdata.length;i++){
    //                 rdata[i].dcl += cTimeLine[i].dcl
    //                 rdata[i].dpj += cTimeLine[i].dpj
    //                 rdata[i].wcl += cTimeLine[i].wcl
    //                 rdata[i].ycl += cTimeLine[i].ycl
    //               }
    //             }
    //           }
    //         }
    //       }
    //     }
    //   }
    // }
    // rdata.reverse()
    // let rrdata = {}
    // for(let i=0;i<['待处理','待评价','已处理','未处理'].length;i++){
    //   let t = []
    //   for(let i1=0;i1<rdata.length;i1++){
    //     switch (i) {
    //       case 0:
    //         t.push(rdata[i1].dcl)
    //         break;
    //       case 1:
    //         t.push(rdata[i1].dpj)
    //         break;
    //       case 2:
    //         t.push(rdata[i1].ycl)
    //         break;
    //       case 3:
    //         t.push(rdata[i1].wcl)
    //         break;
    //     }
    //   }
    //   rrdata[['待处理','待评价','已处理','未处理'][i]] = t
    // }

    // titles.reverse()
    // return {
    //   titles:['待处理','待评价','已处理'],
    //   data:rrdata,
    //   ss:titles,
    //   numData:{
    //     all: this.sumArr(rrdata['待处理']) + this.sumArr(rrdata['待评价']) + this.sumArr(rrdata['已处理']) + this.sumArr(rrdata['未处理']),
    //     dcl: this.sumArr(rrdata['待处理']),
    //     dpj: this.sumArr(rrdata['待评价']),
    //     ycl: this.sumArr(rrdata['已处理']),
    //     wcl: this.sumArr(rrdata['未处理']),
    //   }
    // }
  },
  sumArr(arr) {
    let re = 0
    for (let i = 0; i < arr.length; i++) {
      re += arr[i]
    }
    return re
  },
  comImg(path) {
    return new Promise((resolve, reject) => {
      wx.compressImage({
        src: path,
        quality: 40,
        complete: (res1) => {
          return resolve(res1.tempFilePath)
        }
      })
    })
  },
  selectFile(num = 1) {
    return new Promise(async (resolve, reject) => {
      wx.chooseImage({
        count: num,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePaths = res.tempFilePaths;

          for (let i = 0; i < tempFilePaths.length; i++) {
            tempFilePaths[i] = await this.comImg(tempFilePaths[i])
          }

          return resolve(tempFilePaths)

        }
      })
    })
  },
  setThemeColor(_this) {
    if (wx.getStorageSync('theme') == 'light') {
      wx.setNavigationBarColor({
        backgroundColor: 'white',
        frontColor: '#000000',
      })
    } else {
      wx.setNavigationBarColor({
        backgroundColor: 'black',
        frontColor: '#ffffff',
      })
    }
    _this.setData({
      theme: config.theme[wx.getStorageSync('theme')]
    })
  },
  removeBreak(string) {
    return string.replace(/\n/g, '')
  },
  deleteLongTimeNotUseImg() {
    let re1 = wx.getStorageSync('clearCache')
    if (re1 == '' || re1 == '-1') return
    re1 = parseInt(re1)
    let keys = wx.getStorageInfoSync().keys
    for (let i = 0; i < keys.length; i++) {
      if (keys[i] == 'img-u-addcom.png') continue
      if (keys[i] == 'img-u-addcom-b.png') continue
      if (keys[i].slice(0, 4) == 'img-') {
        let re = JSON.parse(wx.getStorageSync(keys[i]))
        if ((new Date() - new Date(re.time)) > 86400000 * re1) {
          wx.removeStorageSync(keys[i])
        }
      }
    }
  },
  arrDeleteItem(arr, item) {
    let re = []
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] == item) continue
      re.push(arr[i])
    }
    return re
  },
  loading: {
    show(text = '请稍后') {
      wx.showLoading({
        title: text,
      })
    },
    hide() {
      wx.hideLoading()
    }
  },
  navigateTo(_this, pathName, data = {}) {
    wx.navigateTo({
      url: '/pages/' + pathName + '/' + pathName + '?data=' + JSON.stringify({
        statusBarHeight: _this.data.statusBarHeight,
        contentHeight: _this.data.contentHeight,
        loginedUserInfo: _this.data.loginedUserInfo,
        ...data
      }),
    })
  },
  getHTMLString(string) {
    string = string.split('\n')
    let re = ''
    for (let i = 0; i < string.length; i++) {
      re+='<div style="text-indent:2em;line-height:1.5">'
      re+=string[i] + '</div>'
    }
    return re
  }
}

function wordsToHex(words) {
  let hex = '';
  for (let i = 0; i < words.length; i++) {
    let word = words[i];
    // 转换为无符号32位整数，以确保正确的表示  
    let unsignedWord = word >= 0 ? word : 0x100000000 + word;
    // 将每个32位整数转换为4个十六进制字符  
    hex += unsignedWord.toString(16).padStart(8, '0');
  }
  return hex;
}